"""6.4.0 ajout_mode_etude_de_prix

Revision ID: 61d0d891d3c2
Revises: 28a56ce17b2f
Create Date: 2022-03-15 14:34:31.545477

"""

# revision identifiers, used by Alembic.
revision = "61d0d891d3c2"
down_revision = "28a56ce17b2f"

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from caerp.alembic.utils import (
    disable_constraints,
    drop_foreign_key_if_exists,
    drop_index_if_exists,
    foreign_key_exists,
    index_exists,
    column_exists,
    enable_constraints,
)


def update_database_structure():
    # ### commands auto generated by Alembic - please adjust! ###
    if foreign_key_exists("project", "project_ibfk_2"):
        disable_constraints()
        drop_foreign_key_if_exists("project", "project_ibfk_2")
        drop_index_if_exists("project", "IDCompany")
        op.create_foreign_key(
            op.f("fk_project_company_id"),
            "project",
            "company",
            ["company_id"],
            ["id"],
            ondelete="CASCADE",
        )
        enable_constraints()

    op.add_column(
        "project_type",
        sa.Column("price_study_mode", sa.String(length=10), nullable=False),
    )
    for table, column in [
        ("project", "status"),
        ("task", "rank"),
        ("task", "document"),
        ("task", "customerStatus"),
    ]:
        if column_exists(table, column):
            op.drop_column(table, column)
    # ### end Alembic commands ###


def migrate_datas():
    from alembic.context import get_bind
    from zope.sqlalchemy import mark_changed
    from caerp_base.models.base import DBSESSION

    session = DBSESSION()
    conn = get_bind()
    conn.execute("update project_type set price_study_mode='optionnal'")
    mark_changed(session)
    session.flush()


def upgrade():
    update_database_structure()
    migrate_datas()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###
